import {_decorator, Component, Label, Node, Sprite, SpriteFrame} from 'cc';
import {AudioManager} from "db://assets/scripts/common/AudioManager";
import {SkillsController} from "db://assets/scripts/ui/pause/SkillsController";
import {GameManager} from "db://assets/scripts/game/GameManager";
import {UIManager} from "db://assets/scripts/common/UIManager";
import {EventManager} from "db://assets/scripts/common/EventManager";
import {PlayerDataManager} from "db://assets/scripts/common/PlayerDataManager";
import {AudioPaths} from "db://assets/scripts/common/AudioPaths";
import {EventType} from "db://assets/scripts/common/EventType";

const {ccclass, property} = _decorator;

/**
 * 结算控制器
 */
@ccclass('SettlementController')
export class SettlementController extends Component {
    /**
     * 胜利图片
     */
    @property(SpriteFrame)
    public winTitleSF: SpriteFrame;
    /**
     * 失败图片
     */
    @property(SpriteFrame)
    public failTitleSF: SpriteFrame;
    /**
     * 标题
     */
    @property(Sprite)
    public titleSprite: Sprite;
    /**
     * 等级
     */
    @property(Label)
    public levelLabel: Label;
    /**
     * 技能列表
     */
    @property(Node)
    public skillsNode: Node;

    /**
     * 回调
     */
    private callback: Function;

    /**
     * 初始化结算界面
     *
     * @param callback 回调
     */
    public init(callback?: Function) {
        this.callback = callback;
    }

    /**
     * 显示结算界面
     */
    public show() {
        this.levelLabel.string = `${PlayerDataManager.getInstance().getPlayer().floor}`;

        if (GameManager.getInstance().gameStateProxy.getWin()) {
            this.titleSprite.spriteFrame = this.winTitleSF;
        } else {
            this.titleSprite.spriteFrame = this.winTitleSF;
        }

        // 技能列表
        let skillsController = this.skillsNode.getComponent(SkillsController);
        skillsController.init();
    }

    /**
     * 回到主页
     */
    public onBackHome() {
        // 播放声音
        AudioManager.getInstance().playSound(AudioPaths.clickSound);

        // 当游戏失败时
        if (!GameManager.getInstance().gameStateProxy.getWin()) {
            // 失败的时候清空技能和层级
            PlayerDataManager.getInstance().getPlayer().skillIds = [];
            PlayerDataManager.getInstance().getPlayer().floor = 1;
            PlayerDataManager.getInstance().persistPlayer();
        }

        // 隐藏结算界面
        UIManager.getInstance().hideDialog("settlement/settlementPanel");
        // 显示主界面
        UIManager.getInstance().showDialog("home/homePanel");

        // 回调
        this.callback && this.callback();
    }

    /**
     * 再玩一次
     */
    public onPlayAgain() {
        AudioManager.getInstance().playSound(AudioPaths.clickSound);

        UIManager.getInstance().hideDialog("settlement/settlementPanel");

        UIManager.getInstance().showDialog("fight/fightPanel");
        EventManager.dispatchEvent(EventType.ON_GAME_INIT);
    }
}

